package com.bjb.vr.monitor.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: HuJingBo
 * @time: 2022/3/16 10:39
 */
@Slf4j
public class DingDingUtil {

    /**
     * 消息类型
     */
    public static final String PERFORMANCE_ALARM = "performance";
    public static final String SERVER_STATUS_ALARM = "serverStatus";
    /**
     * 发送超时时间10s
     */
    private static final int TIME_OUT = 10000;
    /**
     * 性能监控报警配置
     */
    private static final String PERFORMANCE_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=b9c5c896dcd635c7e221a003ca591355d06d3c3e707a9db2025137b23f552885";
    private static final String PERFORMANCE_SECRET = "SEC499ce424bfccf389ab670bba697e944dd39157a382af1ccfbf6c42ac1392e2e0";
    /**
     * 服务上线下线报警
     */
    private static final String SERVER_STATUS_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=c71398023c05aa99e613df09726354841287719e981e7bf38a33d3bf060d293d";
    private static final String SERVER_STATUS_SECRET = "SECe9168e7ab3b4aeb7e2f960f6df4d7100cf25e3d3c08ffe5125e12b5e892fe412";


    /**
     * @param alarmType  报警方式
     * @param title      内容标题
     * @param content    发送内容
     * @param mobileList 通知具体人的手机号码列表 （可选）
     * @return
     */
    public static String sendMsg(String alarmType, String title, String content, List<String> mobileList) {
        try {
            String webhookUrl = null;
            if (alarmType.equals(SERVER_STATUS_ALARM)) {
                Long timestamp = System.currentTimeMillis();
                String sign = getSign(timestamp, SERVER_STATUS_SECRET);
                webhookUrl = new StringBuilder(SERVER_STATUS_TOKEN)
                        .append("&timestamp=")
                        .append(timestamp)
                        .append("&sign=")
                        .append(sign)
                        .toString();
            } else {
                Long timestamp = System.currentTimeMillis();
                String sign = getSign(timestamp, PERFORMANCE_SECRET);
                webhookUrl = new StringBuilder(PERFORMANCE_TOKEN)
                        .append("&timestamp=")
                        .append(timestamp)
                        .append("&sign=")
                        .append(sign)
                        .toString();
            }
            //是否通知所有人
            boolean isAtAll = false;
            //组装请求内容
            String reqStr = buildReqStr(title, content, isAtAll, mobileList);
            //推送消息（http请求）
            String result = postJson(webhookUrl, reqStr);
            log.info("钉钉推送结果result == {}", result);
            return result;
        } catch (Exception e) {
            log.info("发送群通知异常,异常原因：{}", e.getStackTrace());
            return null;
        }
    }

    /**
     * @param title      内容标题
     * @param content    发送内容
     * @param isAtAll    是否@通知
     * @param mobileList 通知具体人的手机号码列表 （可选）
     * @return
     */
    private static String buildReqStr(String title, String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = Maps.newHashMap();
        contentMap.put("title", title);
        contentMap.put("text", content);
        //通知人
        Map<String, Object> atMap = Maps.newHashMap();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);
        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "markdown");
        reqMap.put("markdown", contentMap);
        reqMap.put("at", atMap);
        return JSON.toJSONString(reqMap);
    }

    /**
     * 封装发送请求
     *
     * @param url    发送地址
     * @param reqStr 发送消息内容
     * @return
     */
    private static String postJson(String url, String reqStr) {
        String body = null;
        try {
            body = HttpRequest.post(url).body(reqStr).timeout(TIME_OUT).execute().body();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }

    /**
     * 自定义机器人获取签名
     * 创建机器人时选择加签获取secret以SE开头
     *
     * @param timestamp
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    private static String getSign(Long timestamp, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        System.out.println("singn:" + sign);
        return sign;
    }

}
